package com.qc31.monitorlib.ui.carreport

import android.text.Html
import android.view.View
import androidx.core.view.isVisible
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import autodispose2.autoDispose
import com.kingja.loadsir.core.LoadService
import com.kingja.loadsir.core.LoadSir
import com.qc31.baselib.base.LazyFragment
import com.qc31.baselib.databinding.IncludeSelectSureBinding
import com.qc31.baselib.loadsie.EmptyCallback
import com.qc31.baselib.rx.LiveDataBus
import com.qc31.baselib.rx.textChangesNoLong
import com.qc31.baselib.utils.isFastClick
import com.qc31.baselib.utils.startActivityTo
import com.qc31.baselib.utils.toast
import com.qc31.comlib.Keys
import com.qc31.comlib.alarm.AlarmDataUtil
import com.qc31.comlib.alarm.ReportSetModel
import com.qc31.comlib.entity.HistoryAlarm
import com.qc31.monitorlib.ui.alarms.AlarmChooseActivity
import com.qc31.monitorlib.ui.alarms.AlarmDetailActivity
import com.qc31.monitorlib.R
import com.qc31.monitorlib.databinding.FragmentReportAlarmBinding
import com.qc31.monitorlib.databinding.IncludeDayChooseBinding
import com.qc31.monitorlib.ui.adapter.AlarmHistoryAdapter
import com.qc31.monitorlib.ui.carmonitor.CarMonitorViewModel
import com.qc31.monitorlib.uitls.DataUtil

/** @Author Jasper @Time 2020/10/15 @Desc 车辆报表 */
class ReportAlarmFragment(private val isAdas: Boolean = false) :
    LazyFragment<FragmentReportAlarmBinding>(FragmentReportAlarmBinding::inflate) {
    private lateinit var loadService: LoadService<Any>
    private lateinit var mDayChooseVB: IncludeDayChooseBinding
    private lateinit var mSureVB: IncludeSelectSureBinding

    private val mActivityVM by activityViewModels<CarMonitorViewModel>()
    private val mViewModel: ReportAlarmViewModel by viewModels()

    private val alarmsAdapter by lazy { AlarmHistoryAdapter(true) }

    override fun initView(view: View) {

        if (ReportSetModel.instance.getNormalAlarmIds().isEmpty()
            || ReportSetModel.instance.getAdasAlarmIds().isEmpty()
        ) AlarmDataUtil.instance.getCarDefaultAlarm(isAdas)

        mViewModel.choose = getString(R.string.desc_selected)
        binding.editRunTime.setText(ReportSetModel.instance.getSpeed(isAdas))
        binding.editRunTime.setSelection(binding.editRunTime.text.length)
        binding.editLongTime.setText(ReportSetModel.instance.getContinueTime(isAdas))
        binding.editLongTime.setSelection(binding.editLongTime.text.length)
        binding.lrTvCarSetAlarm.setRightText(Html.fromHtml(mViewModel.getAlarmIds(isAdas)))
        binding.llAlarmType.visibility = View.GONE

        mSureVB = IncludeSelectSureBinding.bind(binding.root)
        mDayChooseVB = IncludeDayChooseBinding.bind(binding.root)
        mSureVB.tvSure.setText(R.string.desc_sure_query)
        mViewModel.isAdas = isAdas
        loadService = LoadSir.getDefault().register(binding.includeRecycler.recyclerView)

        mActivityVM.carName.observe(this) {
            mViewModel.carName = it
        }

        mActivityVM.carId.observe(this) {
            if (it.isNullOrEmpty()) {
                loadService.showCallback(EmptyCallback::class.java)
            } else {
                mViewModel.carId = it
                if (!mViewModel.isHidden) mViewModel.handleTime()
            }
        }
    }

    override fun initData() {
        if (mViewModel.carId.isEmpty()) showToast(R.string.hint_toast_choose_car)
        loadService.showCallback(EmptyCallback::class.java)

        LiveDataBus.get().with("AlarmChoose", String::class.java).observeStick(this) {
            binding.lrTvCarSetAlarm.setRightText(Html.fromHtml(mViewModel.getAlarmIds(isAdas)))
        }

        initRecycler()

        mViewModel.toastObserver().autoDispose(scopeProvider).subscribe(this::toastObserver)

        mViewModel.alarmSub.hide().autoDispose(scopeProvider).subscribe {
            if (it.list.isNullOrEmpty()) {
                binding.llAlarmType.visibility = View.GONE
                loadService.showCallback(EmptyCallback::class.java)
            } else {
                binding.llAlarmType.visibility = View.VISIBLE
                loadService.showSuccess()
                alarmsAdapter.setList(it.list)
            }
        }
    }

    override fun initEvent() {
        binding.editRunTime.textChangesNoLong().autoDispose(scopeProvider).subscribe {
            if (it.isEmpty()) {
                ReportSetModel.instance.setSpeed("0", isAdas)
            } else {
                ReportSetModel.instance.setSpeed(it, isAdas)
            }

        }

        binding.editLongTime.textChangesNoLong().autoDispose(scopeProvider).subscribe {
            if (it.isEmpty()) {
                ReportSetModel.instance.setContinueTime("0", isAdas)
            } else {
                ReportSetModel.instance.setContinueTime(it, isAdas)
            }

        }

        mSureVB.tvSure.setOnClickListener {
            binding.ivOpenClose.isSelected = false
            binding.llAlarmCondition.isVisible = false
            if (!mViewModel.isHidden && mViewModel.carId.isNotEmpty()) mViewModel.handleTime()
            ReportSetModel.instance.saveParams()

            if (binding.editRunTime.text.isEmpty()) {
                binding.editRunTime.setText("0")
            }

            if (binding.editLongTime.text.isEmpty()) {
                binding.editLongTime.setText("0")
            }
        }

        binding.llQueryCondition.setOnClickListener {
            binding.ivOpenClose.isSelected = !binding.ivOpenClose.isSelected
            binding.llAlarmCondition.isVisible = binding.ivOpenClose.isSelected
        }

        binding.lrTvCarSetAlarm.setOnClickListener {
            val ids = if (isAdas) {
                ReportSetModel.instance.getAdasAlarmIds()
            } else {
                ReportSetModel.instance.getNormalAlarmIds()
            }
            startActivityTo<AlarmChooseActivity>(requireContext()) {
                putExtra(Keys.INTENT_OTHER, isAdas)
                putExtra(Keys.INTENT_DATA, ids)
                putExtra("isCarChoose", true)
            }
        }

        mDayChooseVB.rdbReportYesterday.setOnClickListener {
            mViewModel.timeType = 1
            mViewModel.handleTime()
        }

        mDayChooseVB.rdbReportToday.setOnClickListener {
            mViewModel.timeType = 2
            mViewModel.handleTime()
        }

        mDayChooseVB.rdbReportThree.setOnClickListener {
            mViewModel.timeType = 3
            mViewModel.handleTime()
        }

        mDayChooseVB.rdbReportWeek.setOnClickListener {
            mViewModel.timeType = 4
            mViewModel.handleTime()
        }
    }

    private fun initRecycler() {
        binding.includeRecycler.recyclerView.layoutManager = LinearLayoutManager(requireContext())

        binding.includeRecycler.recyclerView.adapter = alarmsAdapter.apply {
            setOnItemClickListener { adapter, view, position ->
                if (isFastClick()) return@setOnItemClickListener
                val info = adapter.data[position] as HistoryAlarm.TotalAlarms
                if (info.total == 0) {
                    R.string.toast_no_about_alarm.toast(requireContext())
                } else {
                    startActivityTo<AlarmDetailActivity>(requireContext()) {
                        putExtra(Keys.INTENT_CAR_ID, mViewModel.carId)
                        putExtra(Keys.INTENT_PLATE, info.name)
                        putExtra(Keys.INTENT_TITLE, "${info.name}(${info.total})")
                        DataUtil.alarmInfo = info.list
                    }
                }
            }
        }
    }

    //是否隐藏状态变化监听
    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if (hidden) {
            mViewModel.isHidden = true
        } else {
            mViewModel.isHidden = false
            if (mViewModel.carId.isNotEmpty()) mViewModel.handleTime()
        }
    }

}